package com.yuncheng.spcyApi.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author hua
 */
public class HttpProxyUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpProxyUtils.class);

//    private static RequestConfig httpRequestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(10000).build();

    /**
     * 初始化HttpPost请求头
     * @param url 请求地址
     * @return
     */
    private static HttpPost initHttpPost(String url){
        HttpPost httpRequest = new HttpPost(url);
        // 设置请求头，在Post请求中限制了浏览器后才能访问
//        httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
//        httpRequest.addHeader("Accept", "*/*");
//        httpRequest.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpRequest.addHeader("Content-Type", "application/json");
//        httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
//        httpRequest.addHeader("Connection", "keep-alive");
//        httpRequest.addHeader("X-Access-Token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NzAzMzUyODcsInVzZXJuYW1lIjoiYWRtaW4ifQ.jeo2rCx6XWP-9R5bQytsvLhhh-Ib5B5ONovC0s8xLLI");
        return httpRequest;
    }

    /**
     * 接口请求
     * @param url
     * @param jsParam
     * @return
     */
    public static String HttpProxyPost(String url, String jsParam){
        HttpPost httpRequest = initHttpPost(url);

        JSONObject json = JSONObject.parseObject(jsParam);
        httpRequest.setEntity(new StringEntity(json.toString(),"UTF-8"));

        // 设置超时
//        httpRequest.setConfig(httpRequestConfig);

        HttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    return EntityUtils.toString(res, "UTF-8");
                }else {
                    log.error("接口状态异常code：Url: {},msg: {}", url, response.getStatusLine().getStatusCode());
                }
            }else {
                log.error("接口状态异常code：Url: {},msg: {}", url, response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("接口错误异常code：Url: {}; msg: {}", url, e.getMessage());
        }

        return null;
    }

}
